/* JQuery-Bootstrap-Validation
 * A simple plugin for validating the div, form, etc. on Twitter Bootstrap formatted elements.
 *
 * v1.0.3
 *
 * License: MIT <http://opensource.org/licenses/mit-license.php> - see LICENSE file
 *
 * https://github.com/jsantosh14/JQuery-Bootstrap-Validation
 * 
 */
(function($) {
    $.fn.doc_validate = function() {
        var status;
        //text fields required
        $(this).find('.required').each(function(i, obj) {
            element = $(obj);
            if (element.val() == null || element.val() == '' || element.val() == 0) {
                element.showError("This Field Is Mandatory");
                status = false;
            } else {
                element.removeError();
            }
        });
        // validating  checkboxes using data-min and data-max attributes along with .mandatory-cb class
        $(this).find('.mandatory-cb').each(function(i, Obj) {
            e = $(Obj);
            msg = "";
            min = e.attr('data-min')
            max = e.attr('data-max')
            flag = 0;
            if (min && max) {
                msg += " Minimum " + min + " And Maximum " + max;
                if (min > max) {
                    flag = 1;
                     status = false;
                    e.parent("div").find('.text-danger').remove();
                    e.parent("div").append('<span class="text-danger" > <b>data-min</b> is greater than <b>data-max</b>  for this div.<br> Please Change It And Try Again</span>')
                }
            } else if (min) {
                msg += " Minimum " + min
            } else if (max) {
                msg += " Maximum " + max
            }
            if (flag == 0) {
                var checked = e.find('input[type=checkbox]:checked').length;
                if (checked < min || checked > max) {
                 status = false;
                    e.parent("div").find('.text-danger').remove();
                    e.parent("div").append('<span class="text-danger" >Please Select ' + msg + ' checkbox(s).</span>');
                } else {
                    e.parent("div").find('.text-danger').remove();
                }
            }
        });
        // validation for required radio button
        $(this).find('.mandatory-radio').each(function(i, Obj) {
            e = $(Obj);
            e.find('input[type=radio]').each(function(i, obj) {
                value = $('input[type=radio]:checked').val();
                if (value == null) {
                 status = false;
                    e.parent("div").find('.text-danger').remove();
                    e.parent("div").append('<span class="text-danger" >Please Select The Radio Button.</span>');
                } else {
                    e.parent("div").find('.text-danger').remove();
                }


            });
        });


        //making not required fields null before submitting if they are invalid
        $(this).find('.form-control').not('.required').each(function(i, obj) {
            self = $(obj);
            div = self.parent();
            if (div.is('.input-group')) {
                if (div.is('.has-error')) {
                    self.find('input').val("");
                }
                div.parent(".has-error").find('.text-danger').remove();
                div.parent(".has-error").removeClass("has-error");
            } else {
                if (self.parent('div').is('.has-error')) {
                    self.val("");
                }
                self.parent(".has-error").find('.text-danger').remove();
                self.parent(".has-error").removeClass("has-error");
            }
        });
        if (status == false)
            return false;
        else {
            return true;
        }
    };
    // validation for individual fields on events.
    $.fn.validation = function(msg) {

        if (msg == "") {
            msg = "This Field Is Mandatory";
        }
        if (this.val() == null || this.val().length == 0 || this.val() == 0) {
            this.showError(msg);

            return false;
        } else {
            this.removeError();
            return true;
        }

    };
    // updates the styles of the element valid or invalid
    $.fn.removeError = function() {
        div = this.parent();
        if (div.is('.input-group')) {
            div.removeClass("has-error").addClass("has-success");
            div.parent("div").find('.text-danger').remove();
        } else {
            this.parent("div").removeClass("has-error").addClass("has-success");
            this.parent("div").find('.text-danger').remove();
        }
    };

    $.fn.showError = function(msg) {
        div = this.parent();
        //for bootstrap input-group has error class to immediate parent div and span to its parent div
        if (div.is('.input-group')) {
            this.parent('div').addClass("has-error ").removeClass("has-success");
            div.parent("div").find('.text-danger').remove();
            div.parent("div").append('<span class="text-danger" >' + msg + '</span>');
        } else {
            this.parent("div").addClass("has-error ").removeClass("has-success");
            this.parent("div").find('.text-danger').remove();
            this.parent("div").append('<span class="text-danger" >' + msg + '</span>');
        }
    };
}(jQuery));
//binding the elements to update the styles based on  user input
$('.required').bind('change  blur', function() {
    $(this).validation("");
});
// bind check boxes
$('.mandatory-cb :checkbox').click(function() {
    element = $(this).parents('.mandatory-cb').parent('div');
    element.doc_validate();
});
// bind radio buttons
$('.mandatory-radio :radio').click(function() {
    element = $(this).parents('.mandatory-radio').parent('div');
    element.doc_validate();
});



// validation for not required fields
//get todays date in dd/mm/yyyy format.
function Today() {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();
    if (dd < 10) {
        dd = '0' + dd
    }
    if (mm < 10) {
        mm = '0' + mm
    }
    var today = dd + '/' + mm + '/' + yyyy;
    return today
}


// date-picker future
$('input.future').bind('change blur ', function() {
    date = $(this);
    if (date.val() < Today()) {
        date.showError("Select Date From Today.");
    } else {
        date.removeError();
    }
});
// date-picker today
$('input.today').bind('change blur ', function() {
    date = $(this);
    if (date.val() !== Today()) {
        date.showError("Select Today's Date.");
    } else {
        date.removeError();
    }
});
// date-picker past
$('input.past').bind('change blur ', function() {
    date = $(this);
    console.log(date.val())
    if (date.val() > Today() && date.val() != Today() || date.val() == '') {
        date.showError("Select Past Date Till Today.");
    } else {
        date.removeError();
    }
});
//for digits
$('input.digits').bind('change blur ', function() {
    digits = $(this);
    if (/^\d+$/.test(digits.val()) == false) {
        digits.showError("Characters are not allowed");
    } else {
        digits.removeError();
    }
});
//for characters only
$('input.chars').bind('change blur ', function() {
    chars = $(this);
    if (/^[A-z]+$/.test(chars.val()) == false || chars.val().length == 0) {
        chars.showError("Digits are not allowed");

    } else {
        chars.removeError();
    }
});
//for mobile
$('input.mobile').bind('change blur ', function() {
    mobile = $(this);
    if (/^\d+$/.test(mobile.val()) == false) {
        mobile.showError("Characters are not allowed");
    } else {
        if (mobile.val().length != 10) {
            mobile.showError("Must be only 10 digits.");
        } else {
            mobile.removeError();
        }
    }
});
//for email
$('input.email').bind('change blur ', function() {
    //email regex without quotes
    regex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
    email = $(this);
    if (regex.test(email.val()) == false) {

        email.showError("Invalid Email.");
    } else {
        email.removeError();
    }
});

//pan card 
$('input.pan').bind('change blur ', function() {
    //pan regex without quotes
    regex = /^[A-Z]{5}\d{4}[A-Z]{1}$/;
    pan = $(this);
   
    if (!regex.test(pan) || value.length != 10) {
pan.showError("Invalid PAN Card Number.");
      
    }
    else {
        pan.removeError();
    }
});

//range place holder
min = $('input.range').attr('min')
max = $('input.range').attr('max')
$('input.range').attr('placeholder', "Enter Numbers From " + min + " To " + max + " .");
// bind range to validate
$('input.range').bind('change blur ', function() {
    range = $(this);
    if (parseInt(range.val()) > parseInt(this.min)-1 && parseInt(range.val()) < parseInt(this.max)+1) {
       range.removeError();
    } else {
         range.showError("Enter Numbers From " + this.min + " To " + this.max + ".");
    }
});
//password
$('input.password').bind('change blur ', function() {
    password = $(this);
    regex = new RegExp('^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z]).{8,}$');
    if (regex.test(password.val()) == false) {
        password.showError("Password Must be 8 Characters Length And Must Contain 1 Upper-case,1 Lower-case,1 Number,1 Symbol.");
    } else {
        password.removeError();
    }
});
$('input[data-match]').bind('change blur ', function() {
    pass1 = $(this);
    data_match = pass1.attr('data-match');
    pass = $('#' + data_match);

    if (pass.val() == null || pass.val().length == 0) {
        pass.showError("Enter This Field First.");
        pass1.val("");
    } else {
        pass.removeError()
        if (pass.val() != pass1.val()) {
            pass1.showError("Password Doesn't Match.");
        } else {
            pass1.removeError();
        }
    }
});

//

//<--------------------------- global form submit and clear events------------------>
$('.btn-click').click(function(e) {
    parent_div = $(this).closest('.validation');
    if (!$(parent_div).doc_validate()) {
        e.preventDefault();
    }
    //use data-return to call any javascript methods after validation
    else {
        data_return = $(this).attr('data-return');
        if (typeof data_return !== typeof undefined && data_return !== false)
            $('body').append('<script  type="text/javascript">' + data_return + '</script>');
            else
            $('body').append('<script  type="text/javascript">alert("Default Alert!!! Valid Form!!!")</script>');
    }
    return true;
});
// clear all fields
$('.btn-clear').click(function(e) {
    //to disable button click so if defined, server call will no be invoked
    e.preventDefault();
    parent_div = $(this).closest('.validation');
    $(parent_div).find('input[type=text],input[type=password],input[type=email],textarea').each(function(i, obj) {
        $(obj).val("");
        div = $(obj).parent();
        if (div.is('.input-group')) {
            div.parent("div").find('.text-danger').remove();
            div.removeClass("has-error");
            div.removeClass("has-success");
        } else {
            $(obj).parent(".has-error").find('.text-danger').remove();
            $(obj).parent(".has-error").removeClass("has-error");
            $(obj).parent(".has-success").removeClass("has-success");
        }
    });
    $(parent_div).find('select').each(function(i, obj) {
        $(obj).val(0);
        div = $(obj).parent();
        if (div.is('.input-group')) {
            div.parent(".has-error").find('.text-danger').remove();
            div.parent(".has-error").removeClass("has-error");
            div.parent(".has-success").removeClass("has-success");
        } else {
            $(obj).parent(".has-error").find('.text-danger').remove();
            $(obj).parent(".has-error").removeClass("has-error");
            $(obj).parent(".has-success").removeClass("has-success");
        }
    });
    // checkboxes unchecking
    $(parent_div).find('input:checkbox').each(function(i, obj) {
        $(obj).prop('checked', false);
        $(obj).parents("div.mandatory-cb").parent('div').find('.text-danger').remove();
    });
    // radio buttons unchecking
    $(parent_div).find('input:radio').each(function(i, obj) {
        $(obj).prop('checked', false);
        $(obj).parents("div.mandatory-radio").parent('div').find('.text-danger').remove();
    });
});
